﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StorageManager.Properties;
using Astoman.Common;

namespace StorageManager
{
    /// <summary>
    /// Implement this method to receive the SettingChosen event
    /// </summary>
    /// <param name="setting">The setting the user has just chosen</param>
    public delegate void SettingChosen(AzureStorageAccount setting);

    public partial class AccountManager : Form
    {
        private static AzureStorageAccount _currentAccount = null;
        /// <summary>
        /// Returns the account that is currently in use. If no one has been set yet,
        /// the setting that has been used previously is returned. If that also doesn't exist, the first
        /// setting of the AzureStorageAccount.SavePath is returned. If all this fails, null is being returned.
        /// </summary>
        public static AzureStorageAccount CurrentAccount
        {
            get
            {
                if (_currentAccount == null)
                {
                    //First check if preferences say which one is default setting
                    Settings.Default.Reload();
                    if (String.IsNullOrEmpty(Settings.Default.LastAccount))
                    {
                        var names = AzureStorageAccount.GetAllSettingNames(Application.StartupPath);
                        /*If no Setting exists, use first account that can be found*/
                        if (names != null && names.Count > 0)
                        {
                            _currentAccount = AzureStorageAccount.LoadSetting(names[0]);
                        }
                        else
                        {
                            /*No settings, no accounts: Have to return null*/
                            _currentAccount = null;
                        }
                    }
                    else
                    {
                        _currentAccount = AzureStorageAccount.LoadSetting(Settings.Default.LastAccount);
                    }
                }
                return _currentAccount;
            }
            private set { _currentAccount = value; }
        }

        /// <summary>
        /// Subscribe to this event to get notified when the user chooses a different setting.
        /// This normally means that all data has to be reloaded from a different storage account.
        /// </summary>
        public event SettingChosen SettingChosen;

        public AccountManager()
        {
            InitializeComponent();
            if (!String.IsNullOrEmpty(AzureStorageAccount.SavePath))
            {
                SetAccountPath(AzureStorageAccount.SavePath);
                LoadAllSettings();
                SetWindowTitle();
            }
        }

        private void LoadAllSettings()
        {
            var names = AzureStorageAccount.GetAllSettingNames(Application.StartupPath);
            listBoxSettings.Items.Clear();

            listBoxSettings.Items.AddRange(names.ToArray());
        }

        private void SetWindowTitle()
        {
            this.Text = "Settings Manager " + (CurrentAccount == null ? "" : "[Account: " + CurrentAccount.SettingName + "]");
        }

        private void btnSaveSetting_Click(object sender, EventArgs e)
        {
            String accountName = txtBoxAccountName.Text.Trim();
            String sharedKey = txtBoxSharedKey.Text.Trim();
            String errorMessage = AzureStorageAccount.ValidateSetting(accountName, sharedKey);
            if (errorMessage == null)
            {
                var setting = AzureStorageAccount.Create(txtBoxAccountName.Text, txtBoxSharedKey.Text);
                AzureStorageAccount.Save(setting);
                LoadAllSettings();
            }
            else
            {
                MessageBox.Show(this, errorMessage, "Invalid settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void listBoxSettings_SelectedValueChanged(object sender, EventArgs e)
        {
            if (listBoxSettings.Items.Count > 0 && listBoxSettings.SelectedIndex >= 0)
            {
                var setting = AzureStorageAccount.LoadSetting(listBoxSettings.Items[listBoxSettings.SelectedIndex] as String);
                txtBoxAccountName.Text = setting.AccountName;
                txtBoxSharedKey.Text = setting.SharedKey;

                btnLoadSetting.Enabled = true;
            }
        }

        private void listBoxSettings_DoubleClick(object sender, EventArgs e)
        {
            if (listBoxSettings.Items.Count > 0 && listBoxSettings.SelectedIndex >= 0)
            {
                var setting = AzureStorageAccount.LoadSetting(listBoxSettings.Items[listBoxSettings.SelectedIndex] as String);
                UseSetting(setting);
            }
        }

        private void btnLoadSetting_Click(object sender, EventArgs e)
        {
            if (listBoxSettings.Items.Count > 0 && listBoxSettings.SelectedIndex >= 0)
            {
                var setting = AzureStorageAccount.LoadSetting(listBoxSettings.Items[listBoxSettings.SelectedIndex] as String);
                UseSetting(setting);
            }
        }

        private void UseSetting(AzureStorageAccount setting)
        {
            if (setting != null)
            {
                using (new HourGlass())
                {
                    CurrentAccount = setting;
                    SetWindowTitle();
                    if (SettingChosen != null)
                    {
                        SettingChosen(setting);
                    }
                }
                this.Close();
            }
        }

        private void btnSetAccountPath_Click(object sender, EventArgs e)
        {
            var result = folderBrowserDialog1.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                var path = folderBrowserDialog1.SelectedPath;
                Settings.Default.AccountPath = path;
                Settings.Default.Save();
                SetAccountPath(path);
            }
        }

        private void SetAccountPath(string path)
        {
            lblPath.Text = path;
            btnSaveSetting.Enabled = true;
            AzureStorageAccount.SavePath = path;
            LoadAllSettings();
        }

    }
}
